package com.msb.api.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNullApi;

/**
 * @Author: lmf
 * @Create: 2025/3/11 20:21
 * @module
 */
@Configuration
@Slf4j
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        // 构建rabbitTemplate对象

        final RabbitTemplate rabbitTemplate = new RabbitTemplate();
        // 设置connectionFactory
        rabbitTemplate.setConnectionFactory((connectionFactory));

        // 配置config机制
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (!ack) {
                    log.info("【接口模块-发送消息】 消息没有发送到交换机 correlationData={}，cause={}", correlationData, cause);
                }
            }
        });

        // 配置return机制
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {

            @Override
            public void returnedMessage(Message message, int relyCode, String replyText, String exchange,
                                        String routingKey) {

                log.info("【接口模块-发送消息】 消息没有发送到交换机 message={}，exchange={},routingKey={}", new String(message.getBody()),
                        exchange,
                        routingKey);
            }
        });
        return rabbitTemplate;


    }
}
